package org.argus.job.common.model;

import cn.hutool.core.collection.CollectionUtil;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import org.argus.common.core.json.LongJavaScriptSafeSerializer;
import org.argus.common.core.utils.JsonUtils;

import java.util.Arrays;
import java.util.List;

/**
 * @author Echo009
 * @since 2022/3/22
 */
@Data
public class LifeCycle {

    public static final LifeCycle EMPTY_LIFE_CYCLE = new LifeCycle();

    @JsonSerialize(using = LongJavaScriptSafeSerializer.class)
    private Long start;

    @JsonSerialize(using = LongJavaScriptSafeSerializer.class)
    private Long end;

    public static LifeCycle parse(String lifeCycle){
        try {
           return JsonUtils.parseObject(lifeCycle,LifeCycle.class);
        }catch (Exception e){
            // ignore
            return EMPTY_LIFE_CYCLE;
        }
    }

    public static LifeCycle of(List<Long> range) {
        if (CollectionUtil.isEmpty(range)) {
            return EMPTY_LIFE_CYCLE;
        }
        LifeCycle result = new LifeCycle();
        result.start = range.get(0);
        if (range.size() > 1) {
            result.end = range.get(1);
        }
        return result;
    }

    public List<Long> toLifecycleRange() {
        return Arrays.asList(start, end);
    }
}
